package net.cjw.initsb.controller.background;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Strings;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.common.ServiceResult.ServiceResultMsg;
import net.cjw.initsb.entity.ManageUser;
import net.cjw.initsb.service.ManageUserServiceI;
import net.cjw.initsb.utils.SessionUtil;
import net.cjw.initsb.vo.ManageUserVo;

@Api(description = "后台管理员")
@RestController
@RequestMapping("manage_user")
public class ManageUserController {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ManageUserServiceI manageUserServiceI;

	@PostMapping("v{version}/login")
	public ServiceResult<String> login(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version,
			@ApiParam(value = "账号", defaultValue = "test") @RequestParam String username,
			@ApiParam(value = "密码", defaultValue = "123") @RequestParam String password,
			@ApiParam(value = "是否保存一周 true 是", defaultValue = "false") @RequestParam Boolean is_save_week) {

		if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)||is_save_week==null) {
			return ServiceResult.buildError(ServiceResultMsg.REQUEST_PARAM_ERROR_MSG);
		}

		if (version == 1) {
			if (is_save_week) {
				logger.info("保存一周");
				Cookie[] cookies = request.getCookies();
				for (Cookie cookie : cookies) {
					String name = cookie.getName();
					String value = cookie.getValue();
					logger.info("name: " + name);
					logger.info("value: " + value);
					cookie.setMaxAge(604800);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
			ManageUser user = new ManageUser();
			user.setUsername(username);
			user.setPassword(password);
			ServiceResult sr = manageUserServiceI.login(user);
			if (sr.isSuccess()) {
				SessionUtil.setLoginUid(request.getSession(), (String) sr.getData(), null);
			}
			return sr;
		}
		return ServiceResult.buildError(ServiceResultMsg.VERSION_ERROR_MSG);
	}

	@RequiresRoles("admin")
	@PostMapping("v{version}/create")
	public ServiceResult<String> create(
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version,
			@ApiParam(value = "角色id", defaultValue = "") @RequestParam String role_id,
			@ApiParam(value = "账号", defaultValue = "test") @RequestParam String username,
			@ApiParam(value = "昵称", defaultValue = "测试账号") @RequestParam String nickname,
			@ApiParam(value = "密码", defaultValue = "123") @RequestParam String password,
			@ApiParam(value = "真实名称", defaultValue = "我是真实名称") @RequestParam String real_name,
			@ApiParam(value = "上传头像返回的相对url", defaultValue = "/common/image/default_user_avatar.jpg") @RequestParam(required = false) String avatar_url) {

		if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password) || Strings.isNullOrEmpty(role_id)
				|| Strings.isNullOrEmpty(nickname)) {
			return ServiceResult.buildError(ServiceResultMsg.REQUEST_PARAM_ERROR_MSG);
		}
		if (version == 1) {
			ManageUser mu = new ManageUser();
			mu.setUsername(username);
			mu.setPassword(password);
			mu.setNickname(nickname);
			mu.setRealName(real_name);
			mu.setAvatarUrl(avatar_url);
			return manageUserServiceI.create(mu, role_id);
		}
		return ServiceResult.buildError(ServiceResultMsg.VERSION_ERROR_MSG);
	}

	@RequiresRoles("admin")
	@PostMapping("v{version}/update")
	public ServiceResult<String> update(
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version,
			@ApiParam(value = "用户id", defaultValue = "") @RequestParam(required = true) String id,
			@ApiParam(value = "昵称", defaultValue = "我是新昵称") @RequestParam(required = false) String nickname,
			@ApiParam(value = "真实名称", defaultValue = "我是真实名称") @RequestParam(required = false) String real_name,
			@ApiParam(value = "角色id", defaultValue = "") @RequestParam(required = false) String role_id,
			@ApiParam(value = "密码", defaultValue = "1234") @RequestParam(required = false) String password,
			@ApiParam(value = "头像", defaultValue = "/common/image/default_user_avatar.jpg") @RequestParam(required = false) String avatar_url,
			@ApiParam(value = "是否删除 1 是", defaultValue = "true") @RequestParam(required = false) Boolean is_delete,
			@ApiParam(value = "是否禁用 1 是", defaultValue = "true") @RequestParam(required = false) Boolean is_disable) {

		if (Strings.isNullOrEmpty(nickname) && Strings.isNullOrEmpty(password) && Strings.isNullOrEmpty(real_name)
				&& Strings.isNullOrEmpty(avatar_url) && Strings.isNullOrEmpty(role_id) && is_delete == null
				&& is_disable == null) {
			return ServiceResult.buildError(ServiceResultMsg.REQUEST_PARAM_ERROR_MSG);
		}

		if (version == 1) {
			ManageUser user = new ManageUser();
			user.setId(id);
			if (!Strings.isNullOrEmpty(nickname)) {
				user.setNickname(nickname);
			}
			if (!Strings.isNullOrEmpty(password)) {
				user.setPassword(password);
			}
			if (!Strings.isNullOrEmpty(avatar_url)) {
				user.setAvatarUrl(avatar_url);
			}
			if (!Strings.isNullOrEmpty(real_name)) {
				user.setRealName(real_name);
				;
			}
			if (is_delete != null) {
				user.setIsDelete(is_delete);
			}
			if (is_disable != null) {
				user.setIsDisable(is_disable);
			}
			return manageUserServiceI.update(user, role_id);
		}
		return ServiceResult.buildError(ServiceResultMsg.VERSION_ERROR_MSG);
	}

	@GetMapping("v{version}/info")
	public ServiceResult<ManageUserVo> info(HttpServletRequest request,
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version,
			@ApiParam(value = "用户id,不传则查询登录用户信息", defaultValue = "") @RequestParam(required = false) String id) {

		if (version == 1) {
			if (Strings.isNullOrEmpty(id)) {
				id = SessionUtil.getLoginUid(request.getSession());
				if (Strings.isNullOrEmpty(id)) {
					return ServiceResult.buildError("无法获取登录用户信息");
				}
			}
			ManageUser user = new ManageUser();
			user.setId(id);
			return manageUserServiceI.info(user);
		}
		return ServiceResult.buildError(ServiceResultMsg.VERSION_ERROR_MSG);
	}

	@PostMapping("v{version}/logout")
	public ServiceResult<ManageUserVo> logout(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version) {

		if (version == 1) {

			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				cookie.setValue("");
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}

			logger.info("shiro 登出");
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			SessionUtil.logout(request.getSession());
		}
		return ServiceResult.buildSuccess();
	}

	@GetMapping("v{version}/select_all")
	public ServiceResult<Object> selectAll(HttpServletRequest request,
			@ApiParam(value = "版本", defaultValue = "1") @PathVariable("version") Integer version,
			@ApiParam(value = "页数", defaultValue = "1") @RequestParam Integer page_num,
			@ApiParam(value = "数据库最大结果数", defaultValue = "10") @RequestParam Integer max_result) {

		if (version == 1) {
			return manageUserServiceI.selectAll(page_num, max_result);
		}
		return ServiceResult.buildSuccess();
	}

}
